<template>
  <div class="user-management">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32 }">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户名">
                <a-input v-model:value="queryParams.username" placeholder="请输入用户名" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="真实姓名">
                <a-input v-model:value="queryParams.realName" placeholder="请输入真实姓名" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="角色">
                <a-select v-model:value="queryParams.role" placeholder="请选择角色" allowClear>
                  <a-select-option value="admin">管理员</a-select-option>
                  <a-select-option value="teacher">教师</a-select-option>
                  <a-select-option value="student">学生</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="24" :sm="24" style="text-align: right">
              <div class="table-operation-buttons">
                <a-button type="primary" @click="handleSearch">查询</a-button>
                <a-button style="margin-left: 16px" @click="handleReset">重置</a-button>
                <a-button type="primary" style="margin-left: 16px" @click="handleAdd">新增</a-button>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 用户表格 -->
      <a-table
        :columns="columns"
        :data-source="userList"
        :pagination="pagination"
        :loading="loading"
        rowKey="id"
        @change="handleTableChange"
      >
        <!-- 角色列自定义渲染 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'role'">
            <a-tag :color="getRoleColor(record.role)">{{ getRoleText(record.role) }}</a-tag>
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.dataIndex === 'action'">
            <span>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此用户吗?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record)"
              >
                <a>删除</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>

      <!-- 用户表单弹窗 -->
      <a-modal
        :title="formTitle"
        :visible="modalVisible"
        :confirm-loading="confirmLoading"
        @ok="handleSubmit"
        @cancel="handleCancel"
      >
        <a-form :model="form" :rules="rules" ref="formRef" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
          <a-form-item label="用户名" name="username">
            <a-input v-model:value="form.username" placeholder="请输入用户名" />
          </a-form-item>
          <a-form-item label="密码" name="password" v-if="formAction === 'add'">
            <a-input-password v-model:value="form.password" placeholder="请输入密码" />
          </a-form-item>
          <a-form-item label="真实姓名" name="realName">
            <a-input v-model:value="form.realName" placeholder="请输入真实姓名" />
          </a-form-item>
          <a-form-item label="角色" name="role">
            <a-select v-model:value="form.role" placeholder="请选择角色">
              <a-select-option value="admin">管理员</a-select-option>
              <a-select-option value="teacher">教师</a-select-option>
              <a-select-option value="student">学生</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { getUserList, createUser, updateUser, deleteUser } from '@/api/user'
import type { UserInfo } from '@/utils/storage'
import type { UserListParams, UserFormData } from '@/api/user'
import { debounce } from 'lodash-es'

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '真实姓名',
    dataIndex: 'realName',
    key: 'realName',
  },
  {
    title: '角色',
    dataIndex: 'role',
    key: 'role',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
  }
]

// 查询参数
const queryParams = reactive<UserListParams>({
  page: 1,
  pageSize: 10,
  username: '',
  realName: '',
  role: undefined
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 表单相关
const formRef = ref<FormInstance>()
const formTitle = ref<string>('新增用户')
const formAction = ref<'add' | 'edit'>('add')
const form = reactive<UserFormData>({
  username: '',
  password: '',
  realName: '',
  role: 'student'
})

// 表单校验规则
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 状态变量
const loading = ref<boolean>(false)
const modalVisible = ref<boolean>(false)
const confirmLoading = ref<boolean>(false)
const userList = ref<UserInfo[]>([])

// 获取用户列表数据
const fetchUserList = async () => {
  try {
    loading.value = true
    const res = await getUserList(queryParams)
    
    if (res.code === 200 && res.data) {
      userList.value = res.data.result
      pagination.total = res.data.total
      pagination.current = queryParams.page
    } else {
      message.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败', error)
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮点击事件
const handleSearch = debounce(() => {
  queryParams.page = 1
  fetchUserList()
}, 500)

// 重置按钮点击事件
const handleReset = () => {
  queryParams.username = ''
  queryParams.realName = ''
  queryParams.role = undefined
  queryParams.page = 1
  fetchUserList()
}

// 表格变化事件
const handleTableChange = (pag: any) => {
  // 同步更新分页参数
  queryParams.page = pag.current
  queryParams.pageSize = pag.pageSize
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchUserList()
}

// 新增按钮点击事件
const handleAdd = () => {
  formTitle.value = '新增用户'
  formAction.value = 'add'
  form.id = undefined
  form.username = ''
  form.password = ''
  form.realName = ''
  form.role = 'student'
  modalVisible.value = true
}

// 编辑按钮点击事件
const handleEdit = (record: UserInfo) => {
  formTitle.value = '编辑用户'
  formAction.value = 'edit'
  form.id = record.id
  form.username = record.userName
  form.realName = record.realName
  form.role = record.role
  form.password = undefined
  modalVisible.value = true
}

// 删除按钮点击事件
const handleDelete = async (record: UserInfo) => {
  try {
    const res = await deleteUser(record.id)
    if (res.code === 200) {
      message.success('删除用户成功')
      fetchUserList()
    } else {
      message.error(res.message || '删除用户失败')
    }
  } catch (error) {
    console.error('删除用户失败', error)
    message.error('删除用户失败')
  }
}

// 表单提交事件
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value?.validate()
    
    confirmLoading.value = true
    
    // 根据表单状态（新增/编辑）调用不同的API
    const res = formAction.value === 'add' 
      ? await createUser(form)
      : await updateUser(form)
    
    if (res.code === 200) {
      message.success(formAction.value === 'add' ? '新增用户成功' : '编辑用户成功')
      modalVisible.value = false
      fetchUserList()
    } else {
      message.error(res.message || (formAction.value === 'add' ? '新增用户失败' : '编辑用户失败'))
    }
  } catch (error) {
    console.error(formAction.value === 'add' ? '新增用户失败' : '编辑用户失败', error)
  } finally {
    confirmLoading.value = false
  }
}

// 取消表单事件
const handleCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 获取角色文本
const getRoleText = (role: string) => {
  switch (role) {
    case 'admin':
      return '管理员'
    case 'teacher':
      return '教师'
    case 'student':
      return '学生'
    default:
      return '未知'
  }
}

// 获取角色颜色
const getRoleColor = (role: string) => {
  switch (role) {
    case 'admin':
      return 'red'
    case 'teacher':
      return 'green'
    case 'student':
      return 'blue'
    default:
      return 'default'
  }
}

// 页面加载时获取用户列表
onMounted(() => {
  fetchUserList()
})
</script>

<style lang="less" scoped>
.user-management {
  .table-page-search-wrapper {
    margin-bottom: 24px;
    padding: 16px 24px;
    background-color: #fafafa;
    border-radius: 4px;
    
    .table-operation-buttons {
      padding: 8px 0;
      display: flex;
      justify-content: flex-end;
      
      .ant-btn {
        margin-bottom: 12px;
      }
    }
    
    .ant-form-item {
      margin-bottom: 16px;
    }
  }
}
</style> 